<?php
class Image {
	/**
	* @var mixed Mysql connection
	*/
	var $mysqli = null;
	/**
	* @var array User credentials (id, email, type)
	*/
	var $user = null;
	/**
	* @var array Notifications
	*/
	var $notif = array();
	/**
	* @var string Area of concentration
	*/
	var $area = 'image';
	/**
	* @var string Database table to be used
	*/
	var $table = 'Images';
	/**
	* @var mixed Options
	*/
	var $opts = null;
	/**
	* @var string Scene
	*/
	var $scn = '0';
	/**
	* @var string Block
	*/
	var $blk = '0';
	/**
	* @var string Path to image
	*/
	var $path = "data/img/";
	/**
	* @var string Source of image
	*/
	var $srcid = null;
	
	/**
	* Image constructor
	* Initializes image variables for intended request
	* 
	* @param string $area Area of concentration
	* @param array $opts Additional data
	* @param resource $mysqli Current mysql connection
	* @param resource $user User credentials (id, email, type)
	*/
	function __construct($area, $opts, $mysqli, $user) {
		# Require all necessary classes
		require_once "class/setting.php";
		require_once "class/fpdf.php";
		require_once "class/resource.php";
		require_once "class/microorganism.php";
		require_once "class/section.php";
		require_once "class/project.php";
		require_once "class/tool.php";
		
		$this->mysqli = $mysqli;
		$this->user = $user;
		$this->area = $area;
		$this->opts = $opts;
		
		# Select area of concentration
		switch($area) {
			# Microorganisms
			case 'micro':
				$this->table = 'MicroImgs';
				$this->scn = '0';
				$this->blk = '0';
				$this->scn = '0';
				$this->blk = '0';
				$this->path = "data/micro/{$opts['id']}/img/";
				$this->srcid = $opts['id'];
			break;
			
			# Projects
			case 'proj':
				$this->table = 'ProjImgs';
				$this->scn = '0';
				$this->blk = '0';
				$this->scn = '0';
				$this->blk = '0';
				$this->path = "data/proj/{$opts['id']}/img/";
				$this->srcid = $opts['id'];
			break;
			
			# Locations
			case 'loc':
				$this->table = 'LocImgs';
				$this->scn = '0';
				$this->blk = '0';
				$this->path = "data/loc/{$opts['id']}/img/";
				$this->srcid = $opts['id'];
			break;
			
			# Resources
			case 'rsrc':
				$this->table = 'RsrcImgs';
				$this->scn = '0';
				$this->blk = '0';
				$this->path = "data/rsrc/{$opts['id']}/img/";
				$this->srcid = $opts['id'];
			break;
			
			# Marked microorganisms
			case 'mark-micro':
				$this->table = 'MarkMicros';
			break;
			
			# Sections
			case 'proj-sec':
				$this->table = 'ProjSecImgs';
			break;
			
			# Sections
			case 'sec':
				$this->scn = '0';
				$this->blk = '0';
				$this->path = "data/{$opts['sec']}/{$opts['pid']}/sec/{$opts['sid']}/img/";
				$this->srcid = $opts['sid'];
			break;
			
			# Marks
			case 'mark':
				$this->table = 'MarkImgs';
				$this->scn = isset($opts['scn']) ? $opts['scn'] : '0';
				$this->blk = '1';
				$this->srcid = $opts['id'];
				$this->src = $opts['src'];
				$this->path = $opts['path'];
			break;
			
			default:
				$this->path = 'data/img/';
				$this->area = 'img';
			break;
		}
	}
	
	/**
	* Search image
	* Searches for a image based on
	* query string, optional paramaters as constraints,
	* start and end line of result in a mysql resource
	* 
	* @access public
	* @param string $query Keyword/s to look for in the database
	* @param array $opts Contains constraints in search (category, order, author, etc.)
	* @param integer $start Beginning line of searched keyword in mysql resource
	* @param integer $limit End of returned mysql resource as a result of search
	* 
	* @return array Mixed result from mysql query and size of returned rows
	*/
	public function search($query, $opts, $start, $limit) {
		$query = is_array($query) ? $query : Tool::trimout($query);
		$selSize = "SELECT FOUND_ROWS()";
		
		# Search microorganism via ID
		if($opts["c"]=="id" or $opts["c"]=="view") {
			$query = empty($opts['id']) ? $query : $opts['id'];
			
			$sel = "
				SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Images AS T1 WHERE T1.ID='{$query}' ".(in_array($this->user['type'], array('ADMIN','PRIME')) ? '' : "AND T1.Remove='0'")."
					AND ('{$this->user['type']}'='PRIME' OR T1.Visib='PUB' OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
					OR (SELECT COUNT(*) FROM ImgCoeds AS T2 WHERE T2.PID='{$query}' AND T2.CID='{$this->user['id']}') > 0)))
				ORDER BY T1.Title
			";
		}
		# Index page of presentation
		else if($opts["c"]=="guest") {
			# Get all images tagged with microorganism
			$sel = "
				SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Images AS T1 INNER JOIN MicroImgs AS T2
					ON T1.ID=T2.CID WHERE T2.PID='{$query}' AND T1.Visib='PUB' ORDER BY T2.CrtOn
			";
			
			$res1 = $this->mysqli->query($sel);
			$size = $this->mysqli->query($selSize);
			$size1 = $size->fetch_row();
			
			# Get all images marked with microorganism
			$sel = "
				SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Images AS T1 INNER JOIN MarkMicros AS T2
					ON T1.ID=T2.ImgID WHERE T2.MicroID='{$query}' AND T1.Visib='PUB'
			";
			
			$res2 = $this->mysqli->query($sel);
			$size = $this->mysqli->query($selSize);
			$size2 = $size->fetch_row();
			
			# Return results for both searches
			return array($res1, $res2, $size1[0], $size2[0]);
		}
		else {
			$cond = "";
			
			# Select category of search
			switch($opts["c"]) {
				# Image name
				case "name":
					$categ .= "WHERE T1.Name LIKE '%{$query}%' ";
				break;
				
				# Project
				case "proj":
					$categ = "
						INNER JOIN ProjImgs AS T3 INNER JOIN Projects AS T4
							ON T1.ID=T3.CID AND T3.PID=T4.ID
						WHERE T4.Title LIKE '%{$query}%' OR T4.Abstr LIKE '%{$query}%' AND Block='0'
					";
				break;
				
				# Microorganism
				case "micro":
					$categ = "
						INNER JOIN MicroImgs AS T3 INNER JOIN Microorganisms AS T4
							ON T1.ID=T3.CID AND T3.PID=T4.ID
						WHERE T4.Name LIKE '%{$query}%' OR T4.Notes LIKE '%{$query}%' AND Block='0'
					";
				break;
				
				# Multiple ids
				case "multi-id":
					$categ = "WHERE T1.ID IN ('".implode("','", $query)."')";
				break;
				
				# Image title
				case 'exact':
					$categ = "WHERE T1.Title='{$query}'";
				break;
				
				# All images including marks
				case 'title':
				case 'all':
					$categ = "WHERE T1.Title LIKE '%{$query}%' ";
				break;
				
				# All images that are not marks
				default:
					$categ = "WHERE T1.Block='0' ";
				break;
			}
			
			# Partition query string to array
			if(!is_array($query)) $arrQuery = explode(" ", Tool::trimout($query));
			
			# Ordering
			$opts["ob"] = isset($opts["ob"]) ? $opts['ob'] : "Title";
			$opts["oa"] = isset($opts["oa"]) ? $opts["oa"] : "ASC";
			
			# Included words/phrase
			if(!empty($opts["i"])) {
				$cond .= " (T1.Title LIKE '%{$opts["i"]}%' OR T1.Notes LIKE '%{$opts["i"]}%') AND ";
			}
			
			# Excluded words/phrase
			if(!empty($opts["e"])) {
				$arrQuery = explode(", ", $opts["e"]);
				$cond .= "(T1.Title NOT LIKE '%".implode("%' AND T1.Title NOT LIKE '%", $arrQuery)."%') AND ";
				$cond .= "(T1.Notes NOT LIKE '%".implode("%' AND T1.Notes NOT LIKE '%", $arrQuery)."%') AND ";
			}
			
			# Excluded words/phrase
			if(!empty($opts["e"])) {
				$arrQuery = explode(", ", $opts["e"]);
				$cond .= "(T1.Title NOT LIKE '%".implode("%' AND T1.Title NOT LIKE '%", $arrQuery)."%') AND ";
			}
			
			# Creator
			if(!empty($opts["cb"])) {
				if(empty($opts['cbi'])) {
					$name = explode(", ", $opts["cb"]);
					
					# Last name, First name, Mid name
					if(count($name)==3) {
						list($lname, $fname, $mi) = $name;
						$cond .= " (T1.CrtBy IN (SELECT ID FROM Accounts WHERE Lname='".Tool::trimout($lname)."'AND Fname='".Tool::trimout($fname)."') AND ";
					}
					# Email
					else if(strrpos($opts['cb'], '@') > 1) {
						$cond .= " (T1.CrtBy IN (SELECT ID FROM Accounts WHERE Email='{$opts['cb']}')) AND ";
					}
					# Other
					else {
						$cond .= " (T1.CrtBy='%{$query}%') AND ";
					}
				}
				else {
					# Account ID
					$cond .= " (T1.CrtBy='{$opts['cbi']}') AND ";
				}
			}
			
			# Creation date
			if(!empty($opts['co']['s'])) {
				# Date range
				if(!empty($opts["co"]["e"])) {
					$cond .= " (T1.CrtOn BETWEEN '".Tool::trimout($opts["co"]["s"])."' AND '".Tool::trimout($opts["co"]["e"])."') AND ";
				}
				# Exact date
				else {
					$cond .= " (T1.CrtOn='".Tool::trimout($opts["co"]["s"])."') AND ";
				}
			}
			
			# Title
			if(empty($opts["c"]) or ($opts["c"]=="title" and !empty($query))) {
				$cond .= " (T1.Title LIKE '%{$query}%') AND ";
			}
			
			# Removed items
			$cond .= (in_array($this->user['type'], array('ADMIN','PRIME')) and $opts['c']=='remove') ? " T1.Remove='1' AND " : " T1.Remove='0' AND ";
			
			# Limit of returned rows
			$range = (isset($start) and !empty($limit)) ? "LIMIT {$start}, {$limit}" : '';
			
			# Category
			if(empty($categ)) {
				$cond = "
					WHERE {$cond} T1.Scene='1' AND T1.Block='0' AND (T1.Visib='PUB' OR ('{$this->user['type']}'='PRIME')
						OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
						OR (SELECT COUNT(T2.CID) FROM ImgCoeds AS T2 WHERE T2.PID=T1.ID AND T2.CID='{$this->user['id']}') > 0)))
				";
			}
			else {
				$cond = "
					{$categ} AND {$cond} (T1.Visib='PUB' OR ('{$this->user['type']}'='PRIME')
						OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
						OR (SELECT COUNT(T2.CID) FROM ImgCoeds AS T2 WHERE T2.PID=T1.ID AND T2.CID='{$this->user['id']}') > 0)))
				";
			}
			
			# Final search string
			$sel = "
				SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Images AS T1 {$cond} ORDER BY T1.{$opts["ob"]} {$opts["oa"]} {$range}
			";
		}
		
		# Search image in database
		$res = $this->mysqli->query($sel);
		$size = $this->mysqli->query($selSize);
		$size = $size->fetch_row();
		
		# Return search results and size of rows
		return array($res, $size[0]);
	}
	
	/**
	* Create image
	* Create a new image
	* 
	* @access public
	* @param mixed $img Image
	* @param string $title Title
	* @param string $notes Additional information
	* @param mixed $marks Marks in the image
	* @param array $micros Microorganisms
	* @param array $projs Projects
	* @param array $locs Locations
	* @param array $coeds Coeditors
	* @param string $categ Category
	* @param string $visib Visibility
	* 
	* @return boolean true on success, false on failure
	*/
	public function create($img, $title, $notes, $ref, $marks, $micros, $projs, $locs, $coeds, $categ, $visib) {
		$id = Tool::generateID($this->area);
		//$path = $this->area=='mark' ? substr($this->path, 0, strlen($this->path) - (($this->scn=='1' and $this->blk=='0') ? 0 : 19)) : $this->path.$id.'/';
		$path = $this->area=='mark' ? $this->path : $this->path.$id.'/';
		
		# Create directory for image (id)
		if(!is_dir($path)) {
			if(!mkdir($path, 0777, true)) {
				$this->notif[] = 'ERROR: make ftp img dir';
				return false;
			}
		}
		
		# Get extension
		$ext = $this->getExt($img['name']);
		$name = ($this->area=='mark' ? 'm-' : '').uniqid();
		$filename = $name.$ext;
		$filepath = $path.$filename;
		
		# move uploaded file or copy existing file
		if((is_uploaded_file($img['tmp_name']) and move_uploaded_file($img['tmp_name'], $filepath))
			or (file_exists($img['tmp_name']) and rename($img['tmp_name'], $filepath))
		) {
			# Get image dimensions
			list($width, $height) = getimagesize($filepath);
			list($twidth, $theight) = $this->makeThumb($name, $filepath, $path, $img['size'], $img['type'], $width, $height);
			$img['type'] = empty($img['type']) ? $this->getType($img['name']) : $img['type'];
			
			# Insert string for creating image
			$ins = "
				INSERT INTO Images VALUES (
					'{$id}', '{$categ}', '{$visib}', '{$this->scn}', '{$this->blk}',
					'".mysql_real_escape_string(empty($title) ? $img['name'] : $title)."',
					".(empty($notes) ? 'NULL' : "'".mysql_real_escape_string($notes)."'").",
					".(empty($ref) ? 'NULL' : "'".mysql_real_escape_string($ref)."'").",
					'".mysql_real_escape_string($filename)."', '{$img['type']}', '{$img['size']}',
					{$width}, {$height}, '{$filepath}', '{$path}', {$twidth}, {$theight}, '{$path}{$name}-t{$ext}',
					'{$this->area}', ".(empty($this->srcid) ? 'NULL' : "'".$this->srcid."'").",
					'".(empty($coeds["val"]) ? 0 : count($coeds["val"]))."',
					NULL, NULL, 0, NULL, NULL, 0, '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."', '0'
				)
			";
			
			# Insert image in database
			if($this->mysqli->query($ins)) {
				# Append microorganisms
				if(!empty($micros['val'])) {
					$micro = new Microorganism('img', $this->mysqli, $this->user);
					$micro->append($micros, $id, true);
				}
				
				# Append projects
				if(!empty($projs['val'])) {
					$proj = new Project('img', $this->mysqli, $this->user);
					$proj->append($projs, $id);
				}
				
				# Append marks
				if(!empty($marks['coords'])) {
					$rsrc = new Resource('mark-micro', $this->mysqli, $this->user);
					
					foreach($marks['coords'] as $k => $coords) {
						$markresults[$k] = $rsrc->mark(
							true, true, $id, $marks['micro'][$k],
							$coords, $marks['size'][$k], $filepath, (1000/$width)*$height,
							empty($marks['title'][$k]) ? null : $marks['title'][$k],
							empty($marks['notes'][$k]) ? null : $marks['notes'][$k],
							empty($marks['ref'][$k]) ? null : $marks['ref'][$k],
							$categ, $visib
						);
					}
				}
				
				# Append locations
				if(!empty($locs['val']) or !empty($locs['coord'])) {
					
				}
				
				# Append coeditors
				if(!empty($coeds['val'])) {
					$edtr = new Editor('img', $this->mysqli, $this->user);
					$edtr->append($coeds, $id, false);
				}
			}
		}
		# Error in creating image
		else {
			$this->notif[] = "ERROR: ftp put uploaded img";
		}
		
		# Successfully created image
		if(empty($this->notif)) {
			return $id;
		}
		
		# Error occurred
		echo '<pre>', var_dump($this->notif), '</pre>';
		return false;
	}
	
	/**
	* Update sections
	* Update an existing section on the system
	* 
	* @access public
	* @param string $id Document ID
	* @param string $title Title
	* @param string $notes Additional information
	* @param array $micros Microorganisms
	* @param array $rsrcs Resources
	* @param array $coeds Coeditors
	* @param string $categ Category
	* @param string $visib Visibility
	* @param array $rmicros Microorganisms to be removed
	* @param array $rmarks Marks to be removed
	* @param array $rmmicros Microorganisms to be removed in marks
	* @param array $rmrsrcs Resources to be removed in marks
	* @param array $rrsrcs Resources to be removed
	* @param array $rcoeds Coeditors to be removed
	* 
	* @return boolean True on success, false on failure
	*/
	public function update(
		$id, $title, $notes, $ref, $marks, $micros, $rsrcs, $coeds, $categ, $visib,
		$rmicros, $rmarks, $rmmicros, $rmrsrcs, $rrsrcs, $rcoeds
	) {
		# Update string
		$upd = "
			UPDATE Images SET
				Categ='{$categ}', Visib='{$visib}', Title='{$title}', Notes='{$notes}', Ref='{$ref}',
				UpdBy='{$this->user['id']}', UpdOn='".date('Y-m-d H:i:s:ms')."', UpdNo=UpdNo+1
			WHERE ID='{$id}'
		";
		
		# Do mysql update on image
		if($this->mysqli->query($upd)) {
			# Operate on microorganisms
			$micro = new Microorganism('img', $this->mysqli, $this->user);
			$micro->operate($micros, $rmicros, $id, false);
			
			if(!empty($marks['coords'])) {
				$rsrc = new Resource('mark-micro', $this->mysqli, $this->user);
				
				# Iterate through each marks and mark them on image
				foreach($marks['coords'] as $k => $coords) {
					$markresults[$k] = $rsrc->mark(
						true, true, $opts['id'], $marks['micro'][$k],
						$coords, $marks['size'][$k], $filepath, $height,
						$marks['title'][$k], $marks['notes'][$k], $marks['ref'][$k], $categ, $visib
					);
				}
			}
			
			# Remove images
			if(!empty($rmarks['id'])) {
				$this->removeMark($id, $rmarks);
			}
			
			# Remove marked microorganisms
			if(!empty($rmmicros)) {
				$this->removeMicroMark($id, $rmmicros);
			}
			
			# Operate on resources
			$rsrc = new Resource('img', $this->mysqli, $this->user);
			$rsrc->operate($rsrcs, $rrsrcs, $id);
			
			# Operate on coeditors
			$coed = new Editor('img', $this->mysqli, $this->user);
			$coed->operate($coeds, $rcoeds, $id, false);
		}
		# Error in updating image
		else {
			$this->notif[] = "Error in updating details of image {$title}.<br/>";
		}
		
		# Updated image successfully
		if(empty($this->notif)) {
			return true;
		}
		
		# Error occurred
		//echo '<pre>', var_dump($this->notif), '</pre>';
		return false;
	}
	
	/**
	* Delete image
	* Delete an existing image from the system
	* 
	* @access public
	* @param string $id Image ID
	* @param string $path Path to image
	* 
	* @return boolean True on success, false on failure
	*/
	public function delete($id) {
		# Delete image
		$del = "UPDATE Images SET Remove='1' WHERE ID='{$id}'";
		
		if($this->mysqli->query($del)) {
			return true;
		}
		
		echo 'ERROR: del img';
		return false;
	}
	
	/**
	* Recover image
	* Recover a deleted image
	* 
	* @access public
	* @param string $id Image ID
	* 
	* @return boolean true on success, false on failure
	*/
	public function recover($id) {
		# Query string to recover image
		$del = "UPDATE Images SET Remove='0' WHERE ID='{$id}'";
		
		# Recover image in the database
		$res = $this->mysqli->query($del);
		
		# Error occurred in deletion
		if(!$res) {
			echo "ERROR: recover";
			return false;
		}
		
		# Successfully recovered image
		return true;
	} # function recover
	
	/**
	* Upload JSON input for image 
	* Upload json input of images to be added or updated
	* 
	* @access public
	* @param mixed $inputs JSON inputs
	* @param string $action Action to be performed on uploaded inputs
	* @param mixed $opts Additional parameters
	* 
	* @return array Results on each input processed
	*/
	public function upload($inputs, $action, $opts) {
		$results = array();
		$markresults = array();
		
		# Scan each JSON file
		foreach($inputs['tmp_name'] as $i => $path) {
			# Temporary file and directory
			$inpath = 'data/tmp/'.$this->user['id'].'-'.uniqid();
			$input = $inpath.'/'.Tool::trimout($inputs['name'][$i], 25);
			
			# Make temporary directory and move file
			if(!mkdir($inpath, 0777, true)) {
				continue;
			}
			
			if(is_uploaded_file($path)) {
				if(!move_uploaded_file($path, $input)) {
					$results[$i] = false;
					$results['error'][] = $inputs['name'][$i];
					rmdir($inpath);
					continue;
				}
			}
			else if(!file_exists($path) or !rename($path, $input)) {
				$results[$i] = false;
				$results['error'][] = $inputs['name'][$i];
				rmdir($inpath);
				continue;
			}
			
			# Decode JSON contents
			$json = json_decode(utf8_encode(preg_replace( '/\s+/', ' ', file_get_contents($input))));
			
			# Path or file does not exist, skip
			if(!$json or empty($json->filepath)) {// or intval(substr(sprintf('%o', fileperms($filepath)), -6))!=7) {
				$results[$i] = false;
				$results['error'][] = $inputs['name'][$i];
				# Delete json input
				unlink($input);
				rmdir($inpath);
				continue;
			}
			
			# Path to image
			if(file_exists($json->filepath)) {
				$filepath = $json->filepath;
			}
			elseif(!empty($inputs['path'][$i]) and file_exists($inputs['path'][$i].'/'.$json->filepath)) {
				$filepath = $inputs['path'][$i].'/'.$json->filepath;
			}
			else {
				$results[$i] = false;
				$results['error'][] = $inputs['name'][$i];
				# Delete json input
				unlink($input);
				rmdir($inpath);
				continue;
			}
			
			# Title and Notes
			$title = empty($json->title) ? null : $json->title;
			$notes = empty($json->notes) ? null : $json->notes;
			$ref = empty($json->references) ? null : $json->references;
			list($owidth, $oheight) = getimagesize($filepath);
			$height = $oheight*(1000/$owidth);
			$st = $json->settings;
			
			# Microorganisms
			$micros = array();
			foreach($json->microorganisms as $micro) {
				if(!empty($micro->name)) {
					$micros['val'][] = $micro->name;
					$micros['code'][] = empty($micro->code) ? null : $micro->code;
					$micros['auth'][] = empty($micro->auth) ? null : $micro->auth;
					$micros['note'][] = empty($micro->note) ? null : $micro->note;
					$micros['id'] = empty($micro->id) ? null : $micro->id;
				}
			}
			
			# Projects
			$projs = array();
			foreach($json->projects as $proj) {
				if(!empty($proj->title)) {
					$projs['val'][] = $proj->title;
					$projs['abstr'][] = empty($proj->abstract) ? null : $proj->abstract;
					$projs['id'] = empty($proj->id) ? null : $proj->id;
				}
			}
			
			# Locations
			$locs = array();
			foreach($json->locations as $loc) {
				if(!empty($loc->name)) {
					$locs['val'][] = $loc->name;
					$locs['coord'][] = (empty($loc->coords[0]) or empty($loc->coords[1])) ? null : array($loc->coords[0], $loc->coords[1]);
					$locs['id'][] = empty($loc->id) ? null : $loc->id;
				}
			}
			
			# Resources
			$rsrcs = array();
			if(!empty($json->resources)) {
				foreach($json->resources as $rsrc) {
					$rsrcs['title'][] = empty($rsrc->title) ? null : $rsrc->title;
					$rsrcs['notes'][] = empty($rsrc->notes) ? null : $rsrc->notes;
					$rsrcs['links'][] = empty($rsrc->links) ? null : $rsrc->links;
					$rsrcs['id'][] = empty($rsrc->id) ? null : $rsrc->id;
				}
			}
			
			# Marks
			$marks = array();
			foreach($json->marks as $mark) {
				$dim = $mark->dimension;
				
				if((!isset($dim->upperleft[0]) or $dim->upperleft[0]=='')
					or (!isset($dim->upperleft[1]) or $dim->upperleft[1]=='')
					or empty($dim->width) or empty($dim->height)) {
					continue;
				}
				
				$marks['coords'][] = array($dim->upperleft[0], $dim->upperleft[1]);
				$marks['size'][] = array($dim->width, $dim->height);
				
				$marks['title'][] = empty($mark->title) ? null : $mark->title;
				$marks['notes'][] = empty($mark->notes) ? null : $mark->notes;
				
				$mmicros = array();
				foreach($mark->microorganisms as $mmicro) {
					if(!empty($mmicro->name)) {
						$mmicros['val'][] = $mmicro->name;
						$mmicros['code'][] = empty($mmicro->code) ? null : $mmicro->code;
						$mmicros['auth'][] = empty($mmicro->auth) ? null : $mmicro->auth;
						$mmicros['note'][] = empty($mmicro->note) ? null : $mmicro->note;
						$mmicros['ref'][] = empty($mmicro->reference) ? null : $mmicro->reference;
						$mmicros['id'][] = empty($mmicro->id) ? null : $mmicro->id;
					}
				}
				
				$marks['micro'][] = $mmicros;
			}
			
			# Settings
			$coeds = array();
			$categ = 'ADV';
			$visib = 'PRV';
			if(!empty($json->settings)) {
				$st = $json->settings;
				
				# Coeditors
				if(!empty($st->coeditors)) {
					foreach($st->coeditors as $coed) {
						$coeds['val'][] = empty($coed->email) ? $coed->name : $coed->email;
						$coeds['id'][] = empty($coed->id) ? '' : $coed->id;
					}
				}
				
				# Category
				if(!empty($st->category)) {
					switch(strtolower($st->category)) {
						case 'advanced':
						case 'adv':
							$categ = 'ADV';
						break;
						
						case 'basic':
						case 'bsc':
							$categ = 'BSC';
						break;
					}
				}
				
				# Visibility
				if(!empty($st->visibility)) {
					switch(strtolower($st->visibility)) {
						case 'private':
						case 'prv':
							$visib = 'PRV';
						break;
						
						case 'public':
						case 'pub':
							$visib = 'PUB';
						break;
					}
				}
			}
			
			$info = pathinfo($filepath);
			$type = $this->getType($filepath);
			
			# Decide which action to take
			switch($action) {
				case 'make':
					# Create image
					$id = $this->create(
						array (
							'name'=>$info['basename'], 'type'=>$type,
							'tmp_name'=>$filepath, 'error'=>0, 'size'=>filesize($filepath)
						), $title, $notes, $ref, $marks, $micros, $projs, $locs, $coeds, $categ, $visib
					);
					
					$results[$i] = $id;
				break;
				
				case 'edit':
					# Search for image ID if not passed
					if(empty($opts['id'])) {
						list($res, $size) = $this->search($opts['id'], array('c'=>'id'), 0, 10);
						# Image id is found
						if(!empty($size)) {
							$img = $res->fetch_object();
							$opts['id'] = $img->ID;
						}
					}
					
					if(!empty($opts['id'])) {
						# Update image
						$results[$i] = $this->update(
							$opts['id'], $title, $notes, $ref, $marks, $micros, $rsrcs, $coeds, $categ, $visib,
							null, null, null, null, null, null
						);
					}
				break;
			}
			
			# Successful 
			if($results[$i]===false or in_array(false, $markresults, true)) {
				$results['error'][] = $inputs['name'][$i];
			}
			
			# Delete temporary file and directory
			unlink($input);
			rmdir($inpath);
		}
		
		# Return results of json upload
		return $results;
	}
	
	/**
	* Download image
	* Download all allowed details of an document
	* 
	* @access public
	* @param string $id Image ID
	*/
	public function download($id) {
		# Search for image
		list($res, $size) = $this->search($id, array('c'=>'id'), null, null);
		
		# Image not found, redirect
		if(empty($size)) {
			header('refresh: 0.1; url="http://localhost/microwebph/main.php?img=view&fail=get&id='.$id.'"'); return false;
		}
		
		# Get image
		$img = $res->fetch_object();
		
		# Image is not found, redirect
		if(!file_exists($img->Path) or !file_exists($img->Thumb)) {
			header('refresh: 0.1; url="http://localhost/microwebph/main.php?img=view&fail=get&id='.$id.'"'); return false;
		}
		
		# Get settings of image
		$sett = new Setting('img', null, $this->mysqli, $this->user);
		$cond = '';
		
		# Basic: downloadable
		if($img->Categ=='BSC') {
			$cond = "AND T1.Categ='BSC' AND T1.Visib='PUB'";
		}
		# Author, Coeditors, Prime is permitted for download
		else if(!$sett->verify($id)) {
			# If not, redirect
			header('refresh: 0.1; url="http://localhost/microwebph/main.php?img=view&fail=get&id='.$id.'"'); return false;
		}
		
		# Create new PDF file
		$file = new FPDF();
		$file->SetTitle($img->Title.' - MicroWebPH');
		$file->SetAuthor('MicroWebPH (c) 2011');
		$file->AcceptPageBreak();
		$file->AddPage();
		
		$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(72,61,139);
		$file->Write(5, 'MicroWebPH', 'http://localhost/microwebph/');
		$file->SetFont('helvetica', '', 10); $file->SetTextColor(150,150,150);
		$file->Write(5, ' An Online Repository, Management and Retrieval System for Information on Microorganisms'); $file->Ln(); $file->Ln();
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Image thumbnail only
		$file->Image($img->Thumb, null, null, 175); $file->Ln();
		
		$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(72,61,139);
		$file->Write(5, $img->Title, "http://localhost/microwebph/main.php?img=view&id={$id}");
		
		# Notes
		if(!empty($img->Notes)) {
			$file->SetFont('helvetica', '', 10); $file->SetTextColor(0,0,0); $file->Ln();
			$file->Write(5, $img->Notes); $file->Ln(); $file->Ln();
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Microorganisms
		list($micros, $size) = $this->retrieve('micro', $id, null, $cond, '');
		if(!empty($size)) {
			$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Microorganisms'); $file->SetTextColor(0,0,0); $file->Ln();
			$file->SetFont('helvetica', '', 10);
			$i = 1;
			# List all microorganisms
			while($micro = $micros->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(72,61,139);
				$file->Write(5, $micro->Name, "http://localhost/microwebph/main.php?micro=view&id={$micro->ID}"); $file->Ln();
			} $file->Ln();
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Projects
		list($projs, $size) = $this->retrieve('proj', $id, null, $cond, '');
		if(!empty($size)) {
			$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Projects'); $file->SetTextColor(0,0,0); $file->Ln();
			$file->SetFont('helvetica', '', 10);
			$i = 1;
			# List all projects
			while($proj = $projs->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(72,61,139);
				$file->Write(5, $proj->Title, "http://localhost/microwebph/main.php?proj=view&id={$proj->ID}"); $file->Ln();
			}
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Marks
		list($marks, $size) = $this->retrieve('mark-img', $id, null, $cond, '');
		if(!empty($size)) {
			$file->Ln(); $file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(8, 'Marks'); $file->Ln(); $file->SetFont('helvetica', '', 10); $file->SetTextColor(0,0,0);
			
			# List all marks
			while($mark = $marks->fetch_object()) {
				$file->Image($mark->Thumb, null, null, null, 50);
				
				$file->SetFont('helvetica', '', 10); $file->SetTextColor(72,61,139);
				$file->Write(5, $mark->Title.' ', 'http://localhost/microwebph/main.php?img=view&id='.$mark->ID); $file->Ln();
				
				# Notes of each mark
				if(!empty($mark->Notes)) {
					$file->SetTextColor(80,80,80);
					$file->Write(5, $mark->Notes); $file->Ln();
				} $file->Ln();
			}
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Output PDF file
		$file->Output(str_replace(' ', '_', Tool::trimout($img->Title))."-microwebph.pdf", 'i');
	}
	
	/**
	* Process appended and remove images
	* Process on all images associated with an area
	* which are to be appended or removed
	* 
	* @access public
	* @param array $addl Images to be appended
	* @param array $rmvl Images to be removed
	* @param string $id ID of area
	* @param boolean $new Images to be appended, if non-existent, must be created
	*/
	public function operate($addl, $rmvl, $id) {
		if(!empty($addl["val"])) $this->append($addl, $id);
		if(!empty($rmvl)) $this->remove($rmvl, $id);
	}
	
	/**
	* Append images
	* Append images associated to that area
	* 
	* @access public
	* @param array $addl Images to be appended
	* @param string $id ID of area
	*/
	public function append($addl, $id) {
		# Scan through each image title
		foreach($addl['val'] as $i => $title) {
			if(empty($title)) continue;
			
			$ins = '';
			
			# Append image via contained ID
			if(!empty($addl['id'][$i])) {
				$ins = "INSERT INTO {$this->table} VALUES ('{$id}', '{$addl['id'][$i]}', '1', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
			}
			# Search image
			else {
				$res = $this->mysqli->query("SELECT ID FROM Images WHERE Title='{$title}'");
				
				# Image is found, append to area
				if($res and !empty($res->num_rows)) {
					$obj = $res->fetch_object();
					$ins = "INSERT INTO {$this->table} VALUES ('{$id}', '{$obj->ID}', '1', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
				}
			}
		}
		
		# Append image to area
		if(!empty($ins)) {
			if(!$this->mysqli->query($ins)) {
				$this->notif[] = "ERROR: ins area-img {$id} $title.<br/>";
			}
		}
	}
	
	/**
	* Remove images
	* Remove images associated to that area
	* 
	* @access public
	* @param array $rmvl Images to be removed
	* @param string $id ID of area
	*/
	public function remove($rmvl, $id) {
		# Remove all images assoc. with an area
		$del = "DELETE FROM {$this->table} WHERE PID='{$id}' AND CID IN ('".implode("', '", $rmvl)."')";
		
		# Do mysql removal
		if($this->mysqli->query($del)) {
			return true;
		}
		
		$this->notif[] = "ERROR: rem micro<br/>";
	}
	
	/**
	* Get file extension
	* Retrieves a file's extension
	* 
	* @access public
	* @param string $name Name of file
	* 
	* @return string File's extension
	*/
	public function getExt($name) {
		return strtolower(substr($name, strrpos($name, '.')));
	}
	
	/**
	* Get file type
	* Retrieves a file's type
	* 
	* @access public
	* @param string $name Name of file
	* 
	* @return string File's extension
	*/
	public function getType($name) {
		switch(strtolower($this->getExt($name))) {
			case '.jpg':
			case '.jpeg':
				$type = 'image/jpeg';
			break;
			
			case '.gif':
				$type = 'image/gif';
			break;
		}
		
		return $type;
	}
	
	/**
	* Make thumbnail
	* Creates a thumbnail for an image for easy viewing
	* 
	* @access public
	* @param string $file Path to image file
	* @param string $path Destination path of thumbnail
	* @param integer $size Size of image in bytes
	* @param type $type Image's filetype
	* @param integer $srcw Original width of image
	* @param integer $srch Original height of image
	* 
	* @return array Dimension of thumbnail
	*/
	public function makeThumb($name, $file, $path, $size, $type, $srcw, $srch) {
		# Decide quality degrading on image based on its dimension
		if($srcw < 1000 or $srch < 1000) {
			$deg = 75;
			$div = 2;
		}
		elseif($srcw < 2000 or $srch < 2000) {
			$deg = 50;
			$div = 3;
		}
		else {
			$deg = 25;
			$div = 4;
		}
		
		# Create image resource
		$dstw = ceil($srcw/$div);
		$dsth = ceil($srch/$div);
		$imgp = imagecreatetruecolor($dstw, $dsth);
		
		# Decide on type of image to be processed
		switch($type) {
			# JPEG
			case 'image/jpeg':
				# Create new image, resize, and reduce quality
				$img = imagecreatefromjpeg($file);
				imagecopyresized($imgp, $img, 0, 0, 0, 0, $dstw, $dsth, $srcw, $srch);
				imagejpeg($imgp, $path.$name.'-t.jpg', $deg);
			break;
			
			# GIF
			case 'image/gif':
				# Create new image, resize, and reduce quality
				$img = imagecreatefromgif($file);
				imagecopyresized($imgp, $img, 0, 0, 0, 0, $dstw, $dsth, $srcw, $srch);
				imagegif($imgp, $path.$name.'-t.gif');
			break;
			
			# Invalid filetype
			default:
				$this->notif[] = 'ERROR: not valid filetype';
				return false;
			break;
		}
		
		# Remove image resource
		imagedestroy($img);
		imagedestroy($imgp);
		
		# Return the destination width and height of thumbnail
		return array($dstw, $dsth);
	}
	
	/**
	* Remove mark from image
	* Removes mark on an image
	* 
	* @access public
	* @param string $id Image ID
	* @param string $rmarks ID of marks to be removed
	*/
	public function removeMark($id, $rmarks) {
		# Delete marks on image
		$del = "UPDATE Marks SET Remove='1' WHERE ImgID='{$id}' AND ImgMarkID IN ('".implode("', '", $rmarks['id'])."')";
		
		# Remove marks' directory
		/*foreach($rmarks['path'] as $path) {
			if(!is_file($path) or !unlink($path)) {
				$this->notif[] = 'ERROR: unlink img-mark';
			}
		}*/
		
		# Remove marks on database
		if(!$this->mysqli->query($del)) {
			$this->notif[] = "ERROR: del img-mark<br/>";
		}
	}
	
	/**
	* Remove marks' microorganism
	* Removes microorganisms on an image mark
	* 
	* @access public
	* @param string $id Image ID
	* @param string $rmmicros ID of microorganisms to be removed
	*/
	public function removeMicroMark($id, $rmmicros) {
		# Delete marked microorganisms
		$del = "DELETE FROM MarkMicros WHERE ImgID='{$id}' AND MicroID IN ('".implode("', '", $rmmicros)."')";
		
		# Remove in database
		if(!$this->mysqli->query($del)) {
			$this->notif[] = "ERROR: del mark-micro<br/>";
		}
	}
	
	/**
	* Fetch images
	* Fetch images associated with an area
	* 
	* @access public
	* @param string $id ID of area
	* @param int $start Start of return results
	*/
	public function fetch($id, $start) {
		# Images in sections
		if($this->area=='proj-sec') {
			$sel = "
				SELECT T1.* FROM Images AS T1 INNER JOIN {$this->table} AS T2
					ON T1.ID=T2.ImgID AND T2.CID='{$id}' ORDER BY T2.CrtOn LIMIT {$start}, 10
			";
		}
		# Images from other areas
		else {
			$sel = "
				SELECT T1.* FROM Images AS T1 INNER JOIN {$this->table} AS T2
					ON T1.ID=T2.CID AND T2.PID='{$id}' ORDER BY T2.CrtOn LIMIT {$start}, 10
			";
		}
		
		# Search images in database
		$res = $this->mysqli->query($sel) or die();
		
		# Images are found
		if($res and !empty($res->num_rows)) {
			# List all images
			while($img = $res->fetch_object()) { ?>
				<span class="img">
					<a href="main.php?img=view&id=<?php echo $img->ID ?>">
					<img class="stage file locked ghost" src="<?php echo $img->Thumb ?>" alt="<?php echo $img->Title ?>" style="width:<?php echo (125/$img->Height)*$img->Width ?>px"
						data-id="<?php echo $img->ID ?>" data-src="<?php echo $img->Path ?>" data-visib="<?php echo $img->Visib ?>" data-categ="<?php echo $img->Categ ?>"
						data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $img->ID ?>\' target=\'_blank\'><?php echo $img->Title ?></a></span>','stay':'true','x':'l'}"/></a>
					<div class="ctrl-img none">
						<div class="ctrl-main">
							<input name="pic" class="def-img abled" type="checkbox" value="<?php echo $img->Thumb ?>" id="pic<?php echo $img->ID ?>"/> <label for="pic<?php echo $img->ID ?>">Default</label>
							<input name="rimg[]" class="rmv-img abled" type="checkbox" value="<?php echo $img->ID ?>" id="rimg<?php echo $img->ID ?>"/> <label for="rimg<?php echo $img->ID ?>">Remove</label>
						</div>
					</div>
				</span> <?php
			}
		}
	}
	
	/**
	* Present image in index
	* Gets a public image and display it on index page
	* 
	* @access public
	*/
	public function present() {
		$sel = empty($query) ? "SELECT * FROM Images WHERE Visib='PUB' AND Scene='1' AND Block='0' ORDER BY CrtOn LIMIT 1"
			: "SELECT * FROM Images WHERE ID='{$query}' AND Scene='1' AND Block='0' AND Visib='PUB' ORDER By CrtOn";
		
		# Search image in database
		if(($res = $this->mysqli->query($sel)) and !empty($res->num_rows)) {
			$img = $res->fetch_object(); ?>
			<img class="full ghost" src="<?php echo $img->Thumb ?>" alt="<?php echo $img->Title ?>" data-id="<?php echo $img->ID ?>"/> <?php
		}
		# No image is applicable
		else { ?>
			<img class="full ghost" src="template/img.jpg" alt="No image available"/> <?php
		}
	}
	
	/**
	* List image results
	* List all images that are searched for by a user in the index page
	* 
	* @access public
	* @param mixed $result Image results
	*/
	public function itemize($result) {
		$size = $result[2]+$result[3];
		
		# No images were found
		if(empty($size)) {
			return false;
		}
		
		# List all image titles ?>
		<output style="display:none">
			<var id="size"><?php echo $size ?></var>
			<output id="results">
				<div class="sr-header peel off next">Tags (<?php echo $result[2] ?>)</div>
				<ol> <?php
					# List all tagged images
					while($img = $result[0]->fetch_object()) { ?>
						<li class="sr-item" title="<?php echo $img->Title.' - '.Tool::truncate($img->Notes, 250) ?>" data-imid="<?php echo $img->ID ?>" data-src="<?php echo $img->Thumb ?>" data-alt="<?php echo $img->Title ?>"><span><?php echo $img->Title ?></span></li> <?php
					} ?>
				</ol>
				
				<div class="sr-header peel off next">Marks (<?php echo $result[3] ?>)</div>
				<ol> <?php
					# List all marked images
					while($img = $result[1]->fetch_object()) { ?>
						<li class="sr-item" title="<?php echo $img->Title.' - '.Tool::truncate($img->Notes, 250) ?>" data-imid="<?php echo $img->ID ?>" data-src="<?php echo $img->Thumb ?>" data-alt="<?php echo $img->Title ?>"><span><?php echo $img->Title ?></span></li> <?php
					} ?>
				</ol>
			</output>
		</output> <?php
	}
	
	/**
	* Display all images
	* Retrieve all contents of images on a page
	* 
	* @access public
	* @param array $queries IDs of images
	*/
	public function displayAll($queries, $opts) { ?>
		<output> <?php
			if($results = $this->search($queries, $opts, 0, 10)) {
				while($result = $results[0]->fetch_object()) {
					$this->displayContent($result, false);
				}
			} ?>
		</output> <?php
	}
	
	/**
	* Guess image
	* Provides a list of images (guess) on user input
	* Makes selection of image and id faster
	* 
	* @access public
	* @param string $query Image's title
	*/
	public function guess($query) {
		# Search for images matching the query string and constrains passed
		$imgs = $this->search($query, $_REQUEST, 0, 10);
		
		# Image is not found
		if(!$imgs or empty($imgs[1])) {
			echo 1;
			return false;
		}
		
		# List all images
		while($img = $imgs[0]->fetch_object()) { ?>
			<div class="guess img" data-id="<?php echo $img->ID ?>" data-value="<?php echo $img->Title ?>" tabindex="0"
				<?php if(strlen($img->Title) > 50) { ?> data-tool="{'head':'<?php echo $img->Title ?>'}" <?php } ?>>
				<a href="main.php?img=view&id=<?php echo $img->ID ?>"> <?php
					echo Tool::truncate($img->Title, 50); ?></a>
			</div> <?php
		}
		
		if($_REQUEST['s']=='true') { ?>
			<div class="guess-header img query">
				<a href="main.php?img=view&q=<?php echo urlencode($query) ?>" target="_blank" title="<?php echo $query ?>"><?php echo Tool::truncate($query, 30) ?></a>
				<span class="right bold none" title="<?php echo ($found = $imgs[0]->num_rows.' of '.$imgs[1]).' items found' ?>"><?php echo $found ?></span>
			</div> <?php
		}
	}
	
	/**
	* Retrieve details
	* Get all details associated with image to be displayed
	* 
	* @access private
	* @param string $area Area where image is associated
	* @param string $id ID of image
	* @param mixed $img Image object
	* @param string $cond Additional constraints
	* @param string $limit Limit to search results
	* 
	* @return mixed Returned results on search
	*/
	private function retrieve($area, $id, $img, $cond, $limit) {
		$selSize = "SELECT FOUND_ROWS()";
		
		switch($area) {
			# Microorganism
			case 'micro':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Microorganisms AS T1 INNER JOIN MicroImgs AS T2
						ON T1.ID=T2.PID AND T2.CID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Marked microorganism
			case 'mark-micro':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Microorganisms AS T1 INNER JOIN Marks AS T2 INNER JOIN MarkMicros AS T3
						ON T1.ID=T3.MicroID AND T2.ID=T3.PID AND T2.ImgMarkID='{$id}' AND T2.Remove='0' {$cond} ORDER BY T3.CrtOn {$limit}
				";
			break;
			
			# Marked resource
			case 'mark-rsrc':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Resources AS T1 INNER JOIN Marks AS T2 INNER JOIN MarkRsrcs AS T3
						ON T1.ID=T3.RsrcID AND T2.ID=T3.PID AND T2.ImgID='{$id}' AND T2.Remove='0' {$cond} ORDER BY T3.CrtOn {$limit}
				";
			break;
			
			# Marked scene
			case 'mark-scene':
				$sel = "SELECT SQL_CALC_FOUND_ROWS * FROM Images WHERE ID='{$id}'";
			break;
			
			# Marked image
			case 'mark-img':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Images AS T1 INNER JOIN Marks AS T2
						ON T1.ID=T2.ImgMarkID AND T2.ImgID='{$id}' AND T2.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Marked project
			case 'proj':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Projects AS T1 INNER JOIN ProjImgs AS T2
						ON T1.ID=T2.PID AND T2.CID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Marked resource
			case 'rsrc':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Resources AS T1 INNER JOIN ImgRsrcs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
		}
		
		# Search in database
		$res = $this->mysqli->query($sel);
		$size = $this->mysqli->query($selSize);
		$size = $size->fetch_row();
		
		# Return results
		return array($res, $size[0]);
	}
	
	/**
	* Exhibit all images
	* List all images in the main page
	* 
	* @access public
	* @param mixed $imgs List of images from returned search results
	* @param integer $size Size of rows from returned search results
	* @param string $query Query string that was searched for
	* @param array $opts Optional parameters
	* @param integer $start Starting row in mysql returned results
	*/
	public function exhibit($imgs, $size, $query, $opts, $start) {
		# One image to be viewed
		$view = $imgs->num_rows==1;
		# Page number
		$page = ceil(($start+1)/10);
		# Process URL params
		$optstr = Tool::optstrify($opts); ?>
		
		<div id="navis" style="display:inline"> <?php
			# Links to previous ten items ?>
			<a href="main.php?<?php echo $optstr.(empty($query) ? '' : '&q='.$query).(empty($start) ? '&s=0' : '&s='.(intval($start)-10)) ?>"
				class="navi ui ui-button prev <?php if(empty($start)) echo 'disabled' ?>" tabindex="-1" title="Previous 10 items"></a> <?php
			# Links to next ten items ?>
			<a href="main.php?<?php echo $optstr.(empty($start) ? '&s=10' : '&s='.(intval($start)+10)) ?>"
				class="navi ui ui-button next <?php if(($imgs->num_rows<10) or ($imgs->num_rows*$page)>=$size) { echo 'disabled'; } ?>" tabindex="-1" title="Next 10 items"></a>
		</div> <?php
			
		# Labels stage items ?>
		<div id="hnotif" class="escape">
			<span id="query" class="escape iblock" data-tool="{'head':'<?php echo ($all = empty($query)) ? "All images" : $query ?>','x':'l'}"
				<?php if(!($nctrl = empty($_COOKIE['ctrl']['search']))) { echo 'style="width:400px"'; } ?>>
				<?php echo ($all ? "All images" : ($view ? $title : $query)) ?>
			</span>
			
			<span>
				<span id="search-ctrls" <?php if($nctrl) { echo 'class="none"'; } ?>> <?php
					# No. of returned results
					echo '<span id="numresults">Showing '.($imgs->num_rows).' of <b>'.$size.'</b> result(s)</span> on page ';
					
					# Many microorganisms are to be viewed
					$ob = isset($_REQUEST['ob']); $of = true;
					unset($opts['ob']); unset($opts['oa']);
					$optstr = Tool::optstrify($opts);
					
					# Prepare filter options and page selector ?>
					<select id="main-page" class="page navi" data-tool="{'head':'Page'}"> <?php
						for($i=0, $x=$size/10; $i<$x; $i++)	echo "<option ".((isset($opts['s']) and $opts['s']==($i*10)) ? 'selected="selected"' : '').'value="main.php?'.$optstr.(empty($query) ? '' : '&q='.$query).'&s='.($i*10).'">'.($i+1).'</option>';?>
					</select> sorted by <?php
					
					# Prepare filter options ?>
					<select class="navi" data-tool="{'head':'Sort'}">
						<option value="main.php?<?php echo $optstr ?>&ob=title&oa=asc" <?php if($ob and $_REQUEST['ob']=='title') { echo 'selected="selected"'; $of = false; } ?>>Title</option>
						<option value="main.php?<?php echo $optstr ?>&ob=notes&oa=asc" <?php if($ob and $_REQUEST['ob']=='notes') { echo 'selected="selected"'; $of = false; } ?>>Notes</option>
						<option value="main.php?<?php echo $optstr ?>&ob=crtby&oa=asc" <?php if($ob and $_REQUEST['ob']=='crtby') { echo 'selected="selected"'; $of = false; } ?>>Author</option>
						<option value="main.php?<?php echo $optstr ?>&ob=updon&oa=desc" <?php if($ob and $_REQUEST['ob']=='updon') { echo 'selected="selected"'; $of = false; } ?>>Last edited</option>
						<option value="main.php?<?php echo $optstr ?>&ob=shron&oa=desc" <?php if($ob and $_REQUEST['ob']=='shron') { echo 'selected="selected"'; $of = false; } ?>>Last shared</option>
						<option value="main.php?<?php echo $optstr ?>&ob=crton&oa=desc" <?php if($ob and $_REQUEST['ob']=='crton') { echo 'selected="selected"'; $of = false; } ?>>Date created</option>
						<option value="main.php?<?php echo $optstr ?>&ob=id&oa=asc" <?php if($ob and $_REQUEST['ob']=='id') { echo 'selected="selected"'; $of = false; } ?>>ID</option>
					</select>
				</span>
				<span <?php if(!$nctrl) { echo 'class="none"'; } ?>><?php echo "$imgs->num_rows of <b>$size</b> result(s) on page <b>$page</b>";  ?></span> <button type="button" class="navi-details <?php echo (!$nctrl ? 'selected' : '') ?>" data-tool="{'head':'Search controls'}"></button>
			</span>
		</div>
		<div id="exhibit"> <?php
			# Exhibit
			while($img = $imgs->fetch_object()) {
				if(!file_exists($img->Path) or !file_exists($img->Thumb)) { ?>
					<img src="template/img.jpg" alt="Image not found" title="<?php echo $img->Name ?>" style="width:267px"/> <?php
				}
				else { ?>
					<a href="main.php?img=view&id=<?php echo $img->ID ?>" tabindex="-1">
					<img class="stage ghost" tabindex="0" src="<?php echo $img->Thumb ?>" alt="<?php echo $img->Title ?>" style="width:<?php echo (200/$img->Height)*$img->Width ?>px"
						data-id="<?php echo $img->ID ?>" data-src="<?php echo $img->Path ?>" data-visib="<?php echo $img->Visib ?>" data-categ="<?php echo $img->Categ ?>"
						data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $img->ID ?>\' target=\'_blank\'><?php echo $img->Title ?></a></span>','stay':'true','x':'l'}"/></a> <?php
				}
			} ?>
		</div> <?php
	}
	
	/**
	* Display main image stage
	* List all images in the main page
	* 
	* @access public
	* @param mixed $imgs List of images from returned search results
	* @param integer $size Size of rows from returned search results
	* @param string $query Query string that was searched for
	* @param array $opts Optional parameters
	* @param integer $start Starting row in mysql returned results
	*/
	public function displayMain($imgs, $size, $query, $opts, $start) {
		# One image to be viewed
		$view = $imgs->num_rows==1;
		# Page number
		$page = ceil(($start+1)/10);
		# Process URL params
		$optstr = Tool::optstrify($opts); ?>
		
		<div id="side">
			<div id="navis"> <?php
				# Links to previous ten items ?>
				<a href="main.php?<?php echo $optstr.(empty($query) ? '' : '&q='.$query).(empty($start) ? '&s=0' : '&s='.(intval($start)-10)) ?>"
					class="navi ui ui-button prev <?php if(empty($start)) echo 'disabled' ?>" tabindex="-1" title="Previous 10 items"></a> <?php
				# Links to next ten items ?>
				<a href="main.php?<?php echo $optstr.(empty($start) ? '&s=10' : '&s='.(intval($start)+10)) ?>"
					class="navi ui ui-button next <?php if(($imgs->num_rows<10) or ($imgs->num_rows*$page)>=$size) { echo 'disabled'; } ?>" tabindex="-1" title="Next 10 items"></a>
			</div> <?php
			
			# Knobs to stage image ?>
			<div id="knobs"> <?php $i = 1;
				while($img = $imgs->fetch_object()) {
					# Contains data query title, id, tool (tooltip help)
					$title = Tool::truncate($trtitle = $img->Title, 80); ?>
					<div id="knob<?php echo $img->ID ?>" class="knob img <?php if($view) echo "lock" ?>"
						data-id="<?php echo $img->ID ?>" data-tool="{'head':'<b class=\'cool\'><?php echo $title ?></b>','x':'l'}">
						<?php echo $i++; ?>
					</div> <?php
				} ?>
			</div>
		</div> <?php
		
		# Labels stage items ?>
		<div id="hnotif" class="escape"> <?php
			# Shows metadata of all searched items ?>
			<span id="query" class="escape iblock" data-tool="{'head':'<?php echo ($all = (empty($query) and empty($opts['q']))) ? "All images" : (empty($opts['q']) ? $trtitle : $opts['q']) ?>','x':'l'}">
				<?php echo ($all ? "All images" : ($view ? $title : $query)) ?>
			</span>
			<span> <?php
				# Show filter options
				if(!$view) {
					$ob = isset($_REQUEST['ob']); $of = true;
					unset($opts['ob']); unset($opts['oa']);
					$optstr = Tool::optstrify($opts);
					
					# Prepare filter options and page selector ?>
					<select id="main-page" class="page navi" data-tool="{'head':'Page'}"> <?php
						for($i=0, $x=$size/10; $i<$x; $i++)	echo "<option ".((isset($opts['s']) and $opts['s']==($i*10)) ? 'selected="selected"' : '').'value="main.php?'.$optstr.(empty($query) ? '' : '&q='.$query).'&s='.($i*10).'">'.($i+1).'</option>';?>
					</select>
					
					<select class="navi" data-tool="{'head':'Sort'}">
						<option value="main.php?<?php echo $optstr ?>&ob=title&oa=asc" <?php if($ob and $_REQUEST['ob']=='title') { echo 'selected="selected"'; $of = false; } ?>>Title</option>
						<option value="main.php?<?php echo $optstr ?>&ob=notes&oa=asc" <?php if($ob and $_REQUEST['ob']=='notes') { echo 'selected="selected"'; $of = false; } ?>>Notes</option>
						<option value="main.php?<?php echo $optstr ?>&ob=crtby&oa=asc" <?php if($ob and $_REQUEST['ob']=='crtby') { echo 'selected="selected"'; $of = false; } ?>>Author</option>
						<option value="main.php?<?php echo $optstr ?>&ob=updon&oa=desc" <?php if($ob and $_REQUEST['ob']=='updon') { echo 'selected="selected"'; $of = false; } ?>>Last edited</option>
						<option value="main.php?<?php echo $optstr ?>&ob=shron&oa=desc" <?php if($ob and $_REQUEST['ob']=='shron') { echo 'selected="selected"'; $of = false; } ?>>Last shared</option>
						<option value="main.php?<?php echo $optstr ?>&ob=crton&oa=desc" <?php if($ob and $_REQUEST['ob']=='crton') { echo 'selected="selected"'; $of = false; } ?>>Date created</option>
						<option value="main.php?<?php echo $optstr ?>&ob=id&oa=asc" <?php if($ob and $_REQUEST['ob']=='id') { echo 'selected="selected"'; $of = false; } ?>>ID</option>
					</select> <?php
				} ?>
			</span>
		</div> <?php
		
		# Contains all image headers ?>
		<div id="stage"> <?php
			# Reset pointer to first row in mysql result
			$imgs->data_seek(0);
			
			# List all images on its own entry pages
			while($img = $imgs->fetch_object()) {
				# Show first the heading of each image
				$this->displayHeading($img, $view);
			} ?>
		</div> <?php
	}
	
	/**
	* Display an image heading
	* Displays a heading for each image in the results
	* which contains the image's scientific name
	* 
	* @access public
	* @param mixed $img Contains all details of the image
	* @param boolean $cont Checks if content is to be displayed too
	*/
	public function displayHeading($img, $cont) {
		# List an image first as an area with a header that can be selected/clicked by the user in the stage
		# Data included: head (title), id (image id)
		?> <div id="area<?php echo $img->ID ?>" class="stage area img" data-head="<?php echo $img->Title ?>">
			<div class="div-header img <?php echo $cont ? "active lock" : "heading" ?>" data-id="<?php echo $img->ID ?>" data-content="img"
				<?php if(strlen($img->Title)>100) echo 'data-tool="{\'head\':\''.$img->Title.'\',\'x\':\'l\'}"' ?>>
				<a href="main.php?img=view&id=<?php echo $img->ID ?>" class="title img" tabindex="-1">
					<?php echo Tool::truncate($img->Title, 100) ?></a>
			</div> <?php
			
			# Show image's contents if necessary
			if($cont) {
				$this->displayContent($img, $cont);
			} ?>
		</div> <?php
	}
	
	/**
	* Display contents of image
	* Displays the contents of a image, from its title
	* to its associated items in other areas of the system
	* 
	* @access public
	* @param mixed $doc Contains all details of the image
	* @param boolean $cont Checks if only one image is found in results
	*/
	public function displayContent($img, $cont) {
		?> <div class="div-content">
			<form id="form-img<?php echo $id ?>" class="img" name="form-img" method="post" action="process.php?img=edit" enctype="multipart/form-data" novalidate="novalidate">
			<div class="div-upper">
				<div class="div-body">
					<div class="div-peel title"><b>Title</b></span></div>
					<div class="div-case">
						<textarea name="title" class="title reqd read" readonly="readonly" rows="<?php echo ceil(strlen($img->Title)/80) ?>"><?php echo $img->Title ?></textarea>
					</div>
					
					<div class="div-peel peel <?php echo ($empty = (empty($img->Notes) or $img->Notes=='NULL')) ? "on" : "off open" ?> next"><b>Notes</b></div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<textarea name="notes" rows="<?php echo empty($img->Notes) ? '5' : ceil(strlen($img->Notes)/100) ?>" class="read abled" readonly="readonly"><?php echo $img->Notes ?></textarea><br/>
					</div> <?php
					
					//PROJECTS//////////////////////////////////////////////////////////////////////////////////////////////////////////////
					
					list($resProj, $sizeProj) = $this->retrieve('proj', $img->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeProj)) ? "on" : "off open" ?> next proj">
						<b>Projects</b> <span><?php echo $sizeProj ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($proj = $resProj->fetch_object()) { ?>
									<li><a href="main.php?proj=view&id=<?php echo $proj->ID ?>"><?php echo $proj->Title ?></a></li> <?php
								} ?>
							</ol> <?php
						} ?>
					</div> <?php
					
					//MICROORGANISMS//////////////////////////////////////////////////////////////////////////////////////////////////////////////
					
					list($resMicro, $sizeMicro) = $this->retrieve('micro', $img->ID, null, '', 'LIMIT 10');
					list($resMarkMicro, $sizeMarkMicro) = $this->retrieve('mark-micro', $img->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = (empty($sizeMicro) and empty($sizeMarkMicro))) ? "on" : "off open" ?> next micro">
						<b>Microorganisms</b> <span><?php echo $sizeMicros = ($sizeMicro + $sizeMarkMicro) ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<label>Tagged (<?php echo $sizeMicro; ?>)</label> <?php
						if(!empty($sizeMicro)) { ?>
							<ol> <?php
								while($micro = $resMicro->fetch_object()) { ?>
									<li>
										<a href="main.php?micro=view&id=<?php echo $micro->ID ?>"><i><?php
											echo $micro->Name ?></i></a>
										<button type="button" class="remove icon read" data-area="micro" data-id="<?php echo $micro->ID ?>"></button>
									</li> <?php
								} ?>
							</ol> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input type="text" class="micro" name="micro[val][]" placeholder="Scientific name" data-guess="micro=guess" data-name="micro[]"/>
								<button class="append icon" type="button" data-area="micro" data-id="0"></button>
								<input type="hidden" name="micro[id][]" class="abled"/>
							</div>
							<div class="micros"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
						
						<hr/>
						
						<label>Marked (<?php echo $sizeMarkMicro; ?>)</label> <?php
						if(!empty($sizeMarkMicro)) { ?>
							<ol> <?php
								while($micro = $resMarkMicro->fetch_object()) { ?>
									<li>
										<a href="main.php?micro=view&id=<?php echo $micro->ID ?>" class="micro"><i><?php
											echo $micro->Name ?></i></a>
										<button type="button" class="remove icon read" data-area="mmicro" data-id="<?php echo $micro->ID ?>"></button>
									</li> <?php
								} ?>
							</ol><?php
						}  ?>
					</div> <?php
					
					if($img->Block=='1') {
						//SCENE//////////////////////////////////////////////////////////////////////////////////////////////////////////////
						
						list($resScene, $sizeScene) = $this->retrieve('mark-scene', $img->SrcID, null, '', 'LIMIT 10'); ?>
						
						<div class="div-peel peel <?php echo ($empty = empty($sizeScene)) ? "on" : "off open" ?> next mark">
							<b>Source</b> <span><?php echo $sizeScene ?></span>
						</div>
						<div class="div-case <?php if($empty) echo "none" ?>"> <?php
							if(!$empty) { $scene = $resScene->fetch_object(); ?>
								<a href="main.php?img=view&id=<?php echo $scene->ID ?>">
								<img class="stage file locked ghost" src="<?php echo $scene->Thumb ?>" alt="<?php echo $scene->Title ?>" style="width:<?php echo intval((125/$scene->Height)*$scene->Width) ?>px"
									data-id="<?php echo $scene->ID ?>" data-src="<?php echo $scene->Path ?>" data-visib="<?php echo $scene->Visib ?>" data-categ="<?php echo $scene->Categ ?>"
									data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $scene->ID ?>\' target=\'_blank\'><?php echo $scene->Title ?></a></span>','x':'l','stay':1}"/></a> <?php
							} ?>
						</div> <?php
					}
					
					//MARKS//////////////////////////////////////////////////////////////////////////////////////////////////////////////
					
					list($resMark, $sizeMark) = $this->retrieve('mark-img', $img->ID, null, '', ''); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeMark)) ? "on" : "off open" ?> next mark">
						<b>Marks</b> <span><?php echo $sizeMark ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) {
							while($mark = $resMark->fetch_object()) { ?>
								<span class="mark">
									<a href="main.php?img=view&id=<?php echo $mark->ID ?>">
									<img class="stage file locked ghost" src="<?php echo $mark->Thumb ?>" alt="<?php echo $mark->Title ?>" style="width:<?php echo intval((125/$mark->Height)*$mark->Width) ?>px"
										data-id="<?php echo $mark->ID ?>" data-src="<?php echo $mark->Path ?>" data-visib="<?php echo $mark->Visib ?>" data-categ="<?php echo $mark->Categ ?>"
										data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $mark->ID ?>\' target=\'_blank\'><?php echo $mark->Title ?></a></span>','x':'l','stay':1}"/></a>
									<div class="ctrl-img none">
										<div class="ctrl-main">
											<input name="rmark[id][]" class="rmv-img abled" type="checkbox" value="<?php echo $mark->ID ?>" data-area="img" id="rmark<?php echo $mark->ID ?>"/> <label for="rmark<?php echo $mark->ID ?>">Remove</label>
											<input name="rmark[path][]" class="abled" type="hidden" value="<?php echo $mark->Path ?>"/>
										</div>
									</div>
								</span> <?php
							}
						} ?>
						<!--<a class="fetch rsrc tick" data-area="mark" data-id="<?php echo $img->ID ?>" data-start="10">Show more</a>-->
					</div> <?php
					
					//RESOURCES//////////////////////////////////////////////////////////////////////////////////////////////////////////////
					
					list($resRsrc, $sizeRsrc) = $this->retrieve('rsrc', $img->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeRsrc)) ? "on" : "off open" ?> next rsrc">
						<b>Resources</b> <span><?php echo $sizeRsrc ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($rsrc = $resRsrc->fetch_object()) { ?>
									<li class="rsrc">
										<a href="main.php?rsrc=view&id=<?php echo $rsrc->ID ?>"><?php echo $rsrc->Title ?></a>
										<button type="button" class="remove icon read" data-area="rsrc" data-id="<?php echo $rsrc->ID ?>"></button>
									</li> <?php
								} ?>
							</ol>
							<a class="fetch rsrc tick" data-area="img" data-id="<?php echo $img->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input type="text" class="rsrc" name="rsrc[val][]" placeholder="Resource title" data-guess="rsrc=guess"/>
								<button class="append icon" type="button" data-area="rsrc" data-id="0"></button>
								<input type="hidden" name="rsrc[id][]" class="abled"/>
							</div>
							<div class="rsrcs"></div>
						</div>
						
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div>
					
					<div class="div-peel peel <?php echo ($empty = (empty($img->Ref) or $img->Ref=='NULL')) ? "on" : "off open" ?> next ref">
						<b>References</b></div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<textarea name="ref" rows="<?php echo $empty ? '3' : ceil(strlen($img->Ref)/100) ?>" class="read abled" readonly="readonly"> <?php
							echo $img->Ref ?></textarea>
					</div> <?php
					
					//FILES////////////////////////////////////////////////////////////////////////////////////////////////////////////// ?>
					
					<div class="div-peel peel on next file none"><b>Files</b></div>
					<div class="div-case none">
						<input type="file" name="file[]" multiple="multiple" accept="image/jpeg,image/gif,application/pdf"/>
					</div> <?php
					
					//INPUT////////////////////////////////////////////////////////////////////////////////////////////////////////////// ?>
					
					<div class="div-peel peel on next file none"><b>Update</b></div>
					<div class="div-case file none">
						<input name="input[]" type="file" class="file" accept="application/json"/>
					</div> <?php
					
					//SETTINGS////////////////////////////////////////////////////////////////////////////////////////////////////////////*/ ?>
					
					<div class="div-peel peel on next safe none"><b>Settings</b><span class="setting help"></span></div>
					<div class="div-case none safe"></div>
				</div>
				
				<div class="div-head">
					<a href="#"><img class="stage ghost profile" src="<?php echo $img->Thumb ?>" alt="<?php echo $img->Title ?>"
						style="height:<?php echo (200/$img->Width)*$img->Height ?>px" data-src="<?php echo $img->Path ?>"
						data-id="<?php echo $img->ID ?>" data-visib="<?php echo $img->Visib ?>" data-categ="<?php echo $img->Categ ?>"/></a>
					
					<div class="controls">
						<button class="open img dial" type="button">Open</button><hr/>
						
						<button class="share dial" data-area="img" data-id="<?php echo $img->ID ?>" type="button"><span>Share</span></button> <?php
						
						$sett = new Setting('img', null, $this->mysqli, $this->user);
						$verified = $sett->verify($img->ID) and in_array($this->user['type'], array('PRIME','ADMIN'));
						
						if($img->Categ=='BSC' or $verified) { ?>
							<a href="process.php?img=get&id=<?php echo $img->ID ?>"><span class="dload dial button"><span>Download</span></span></a> <?php
						} ?><hr/>
						
						<button class="details dial" type="button" data-area="img" data-id="<?php echo $img->ID ?>" data-name="<?php echo $img->Title ?>"><span>Details</span></button>
						
						<button class="stat dial peel on next" type="button"><b>Contents</b></button>
						<ul class="metas none">
							<li class="meta">Projects <span><?php echo $sizeProj ?></span></li>
							<li class="meta">Microorganisms <span><?php echo $sizeMicros ?></span></li>
							<li class="meta">Resources <span><?php echo $sizeRsrc ?></span></li>
							<li class="meta">Marks <span><?php echo $sizeMark ?></span></li>
						</ul> <?php
						
						if($verified) { ?><hr/>
							<button class="edit dial" data-area="img" data-id="<?php echo $img->ID ?>" type="reset"><span>Edit</span></button> <?php
						} ?>
					</div>
				</div>
				
				<div class="div-mind">
					<input name="id" type="hidden" class="id abled" value="<?php echo $img->ID ?>"/>
					<input name="upd" type="checkbox" class="abled none" value="<?php echo $img->ID ?>"/>
					<input name="del" type="checkbox" class="del abled none" value="<?php echo $img->ID ?>"/>
					<input name="recov" type="checkbox" class="recov abled" value="<?php echo $img->ID ?>"/>
					<input name="path" type="hidden" class="del abled none" value="<?php echo $img->Path ?>"/>
				</div>
			</div>
			
			<div class="div-dial"> <?php
				if($img->Remove=='0') { ?>
					<button class="delete tick read left" type="button" form="form-img<?php echo $img->ID ?>" data-area="img">Delete</button> <?php
				}
				else { ?>
					<button class="recover tick read left" type="button" form="form-img<?php echo $img->ID ?>" data-area="img">Recover</button> <?php
				} ?>
				<button type="button" form="form-img<?php echo $img->ID ?>" class="cancel edit read">Cancel</button>
				<button type="submit" class="read">Update</button> <?php
				
				if(!$cont) { ?>
					<button type="button" class="close-content reset">Close</button> <?php
				} ?>
			</div>
			</form> </div> <?php
	}
}
?>